<!DOCTYPE html>
<!-- add by xfZhang 20250612  博客地址：https://gitee.com/zxfmike 欢迎联系 -->
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JSON结果生成器</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- Tailwind CSS 配置 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#FF7D00',
                        success: '#36D399',
                        warning: '#FBBD23',
                        danger: '#F87272',
                        dark: '#1E293B',
                        light: '#F8FAFC'
                    },
                    fontFamily: {
                        inter: ['Inter', 'sans-serif'],
                    },
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-shadow {
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px rgba(22, 93, 255, 0.15);
            }
            .gradient-bg {
                background: linear-gradient(135deg, #165DFF 0%, #0E3C9E 100%);
            }
            .input-focus {
                @apply focus:ring-2 focus:ring-primary/50 focus:border-primary;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-inter text-dark">
    <!-- 导航栏 -->
    <nav class="gradient-bg text-white py-4 shadow-md">
        <div class="container mx-auto px-4">
            <div class="flex justify-between items-center">
                <div class="flex items-center space-x-2">
                    <i class="fa fa-calculator text-2xl"></i>
                    <h1 class="text-xl md:text-2xl font-bold">JSON结果生成器</h1>
                </div>
                <button class="md:hidden text-xl">
                    <i class="fa fa-bars"></i>
                </button>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8">
        <!-- 介绍卡片 -->
        <div class="bg-white rounded-xl card-shadow p-6 mb-8">
            <h2 class="text-2xl font-bold mb-4 text-primary">如何使用</h2>
            <p class="text-gray-600 mb-4">
                结果生成器可以根据您指定的预期结果和初始乘数，生成符合条件的基本数和乘数组合。
                系统会确保最终计算结果与预期结果的误差严格控制在10%以内。
            </p>
            <div class="grid grid-cols-1 md:grid-cols-3 gap-4 mt-6">
                <div class="bg-blue-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
                            <i class="fa fa-edit"></i>
                        </div>
                        <h3 class="ml-3 font-semibold">输入参数</h3>
                    </div>
                    <p class="text-sm text-gray-600">在表单中输入您期望的结果值和初始乘数。</p>
                </div>
                <div class="bg-green-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div class="w-8 h-8 rounded-full bg-success/10 flex items-center justify-center text-success">
                            <i class="fa fa-magic"></i>
                        </div>
                        <h3 class="ml-3 font-semibold">生成结果</h3>
                    </div>
                    <p class="text-sm text-gray-600">点击"生成"按钮，系统会计算并生成符合条件的组合。</p>
                </div>
                <div class="bg-yellow-50 p-4 rounded-lg">
                    <div class="flex items-center mb-2">
                        <div class="w-8 h-8 rounded-full bg-warning/10 flex items-center justify-center text-warning">
                            <i class="fa fa-bar-chart"></i>
                        </div>
                        <h3 class="ml-3 font-semibold">查看结果</h3>
                    </div>
                    <p class="text-sm text-gray-600">在结果区域查看生成的组合和详细计算过程。</p>
                </div>
            </div>
        </div>

        <!-- 输入表单 -->
        <div class="bg-white rounded-xl card-shadow p-6 mb-8">
            <h2 class="text-xl font-bold mb-6 flex items-center">
                <i class="fa fa-sliders text-primary mr-2"></i>
                参数设置
            </h2>
            <form id="generatorForm" class="space-y-4">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                    <div>
                        <label for="expectedResult" class="block text-sm font-medium text-gray-700 mb-1">预期结果</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-line-chart text-gray-400"></i>
                            </div>
                            <input type="number" id="expectedResult" name="expectedResult" 
                                class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg shadow-sm input-focus"
                                placeholder="例如: 2000" value="2000" required>
                        </div>
                        <p class="mt-1 text-xs text-gray-500">生成结果将在这个值的±10%范围内</p>
                    </div>
                    <div>
                        <label for="initialMultiplier" class="block text-sm font-medium text-gray-700 mb-1">初始乘数</label>
                        <div class="relative">
                            <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <i class="fa fa-times text-gray-400"></i>
                            </div>
                            <input type="number" id="initialMultiplier" name="initialMultiplier" 
                                class="w-full pl-10 pr-3 py-2 border border-gray-300 rounded-lg shadow-sm input-focus"
                                placeholder="例如: 1" value="1" required>
                        </div>
                        <p class="mt-1 text-xs text-gray-500">基本乘数，将与其他乘数相加</p>
                    </div>
                </div>
                <div class="pt-4">
                    <button type="submit" id="generateButton" class="w-full md:w-auto bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg shadow transition-all duration-300 flex items-center justify-center">
                        <i class="fa fa-refresh mr-2"></i>
                        生成结果
                    </button>
                </div>
            </form>
        </div>

        <!-- 结果展示 -->
        <div id="resultContainer" class="hidden bg-white rounded-xl card-shadow p-6 mb-8">
            <div class="flex justify-between items-center mb-6">
                <h2 class="text-xl font-bold flex items-center">
                    <i class="fa fa-table text-primary mr-2"></i>
                    生成结果
                </h2>
                <div class="flex space-x-2">
                    <button id="copyResult" class="bg-gray-100 hover:bg-gray-200 text-gray-700 py-1 px-3 rounded-lg text-sm flex items-center transition-colors">
                        <i class="fa fa-copy mr-1"></i>
                        复制
                    </button>
                    <button id="regenerate" class="bg-secondary hover:bg-secondary/90 text-white py-1 px-3 rounded-lg text-sm flex items-center transition-colors">
                        <i class="fa fa-random mr-1"></i>
                        重新生成
                    </button>
                </div>
            </div>

            <!-- 结果摘要 -->
            <div class="bg-blue-50 rounded-lg p-4 mb-6">
                <div class="grid grid-cols-1 md:grid-cols-4 gap-4">
                    <div class="text-center">
                        <p class="text-sm text-gray-600">预期结果</p>
                        <p class="text-2xl font-bold text-primary" id="expectedValue">2000</p>
                    </div>
                    <div class="text-center">
                        <p class="text-sm text-gray-600">最终结果</p>
                        <p class="text-2xl font-bold text-success" id="finalValue">1980</p>
                    </div>
                    <div class="text-center">
                        <p class="text-sm text-gray-600">误差率</p>
                        <p class="text-2xl font-bold" id="errorRate">1.0%</p>
                    </div>
                    <div class="text-center">
                        <p class="text-sm text-gray-600">计算方式</p>
                        <p class="text-lg font-semibold" id="calculationMethod">(200 + 500 + 300 + 100) × (1 + 20)</p>
                    </div>
                </div>
            </div>

            <!-- 基本数表格 -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-cubes text-primary mr-2"></i>
                    基本数组合
                </h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">主键</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">子键</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数值</th>
                            </tr>
                        </thead>
                        <tbody id="baseNumbersTable" class="bg-white divide-y divide-gray-200">
                            <!-- 数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
                <div class="mt-2 text-right font-semibold">
                    总计: <span id="totalBase" class="text-primary">1100</span>
                </div>
            </div>

            <!-- 乘数表格 -->
            <div class="mb-8">
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-multiply text-primary mr-2"></i>
                    乘数组合
                </h3>
                <div class="overflow-x-auto">
                    <table class="min-w-full divide-y divide-gray-200">
                        <thead class="bg-gray-50">
                            <tr>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">序号</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">主键</th>
                                <th scope="col" class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">数值</th>
                            </tr>
                        </thead>
                        <tbody id="multipliersTable" class="bg-white divide-y divide-gray-200">
                            <!-- 数据将通过JavaScript动态填充 -->
                        </tbody>
                    </table>
                </div>
                <div class="grid grid-cols-2 gap-4 mt-4">
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <p class="text-sm text-gray-600">初始乘数</p>
                        <p class="font-semibold" id="initialMultiplierValue">1</p>
                    </div>
                    <div class="bg-gray-50 p-3 rounded-lg">
                        <p class="text-sm text-gray-600">总乘数</p>
                        <p class="font-semibold text-success" id="totalMultiplierValue">21</p>
                    </div>
                </div>
            </div>

            <!-- 详细JSON数据 -->
            <div>
                <h3 class="text-lg font-semibold mb-4 flex items-center">
                    <i class="fa fa-code text-primary mr-2"></i>
                    详细数据
                </h3>
                <div class="bg-gray-800 text-gray-200 rounded-lg p-4 overflow-x-auto text-sm">
                    <pre id="jsonResult">{
    "oddsTable": {
        "1": { "8": 200, "9": 200, "10": 500, "11": 500, "12": 1000 },
        "2": { "8": 50, "9": 50, "10": 200, "11": 200, "12": 500 },
        "3": { "8": 40, "9": 40, "10": 100, "11": 100, "12": 300 },
        "4": { "8": 30, "9": 30, "10": 40, "11": 40, "12": 240 },
        "5": { "8": 20, "9": 20, "10": 30, "11": 30, "12": 200 },
        "6": { "8": 16, "9": 16, "10": 24, "11": 24, "12": 160 },
        "7": { "8": 10, "9": 10, "10": 20, "11": 20, "12": 100 },
        "8": { "8": 8, "9": 8, "10": 18, "11": 18, "12": 80 },
        "9": { "8": 5, "9": 5, "10": 15, "11": 15, "12": 40 },
        "15": { "4": 60, "5": 60, "6": 2000 }
    },
    "multiplierMapping": {
        "10": [100, 150, 200, 250, 500],
        "11": [50, 55, 60, 65, 80],
        "12": [10, 12, 15, 20, 25],
        "13": [2, 3, 5, 6, 8]
    },
    "baseNumbers": [
        { "mainKey": 1, "subKey": 8, "value": 200 },
        { "mainKey": 2, "subKey": 12, "value": 500 },
        { "mainKey": 3, "subKey": 10, "value": 300 },
        { "mainKey": 7, "subKey": 10, "value": 100 }
    ],
    "multipliers": [
        { "mainKey": 12, "value": 20 }
    ],
    "totalBase": 1100,
    "totalMultiplier": 21,
    "finalResult": 23100,
    "expectedResult": 2000,
    "error": 0.01
}</pre>
                </div>
            </div>
        </div>

        <!-- 加载状态 -->
        <div id="loadingState" class="hidden bg-white rounded-xl card-shadow p-8 text-center">
            <div class="animate-spin rounded-full h-16 w-16 border-t-4 border-b-4 border-primary mx-auto mb-4"></div>
            <h3 class="text-lg font-semibold text-primary">正在生成结果...</h3>
            <p class="text-gray-600 mt-2">这可能需要几秒钟时间，请稍候...</p>
        </div>

        <!-- 错误提示 -->
        <div id="errorState" class="hidden bg-white rounded-xl card-shadow p-8 text-center">
            <div class="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center mx-auto mb-4">
                <i class="fa fa-exclamation-triangle text-2xl text-danger"></i>
            </div>
            <h3 class="text-lg font-semibold text-danger">生成失败</h3>
            <p class="text-gray-600 mt-2" id="errorMessage">无法生成符合条件的结果，请尝试调整参数。</p>
            <button id="tryAgain" class="mt-4 bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg shadow transition-all duration-300">
                再试一次
            </button>
        </div>
    </main>

  <!-- 页脚 -->
    <footer class="bg-dark text-white py-6 mt-10">
        <div class="container mx-auto px-4">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    <div class="flex items-center space-x-2">
                        <i class="fa fa-calculator text-xl"></i>
                        <span class="font-bold">结果生成器</span>
                    </div>
                    <p class="text-gray-400 text-sm mt-1">根据预期结果和初始乘数生成合理的组合</p>
                </div>
                <div class="flex space-x-4">
                    <a href="javascript:window.open('https://gitee.com/zxfmike')" class="text-gray-400 hover:text-white transition-colors">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                </div>
            </div>
            <div class="border-t border-gray-800 mt-6 pt-6 text-center text-gray-500 text-sm">
                &copy; 2025 https://gitee.com/zxfmike | 保留所有权利
            </div>
        </div>
    </footer>

    <!-- 成功提示模态框 -->
    <div id="successModal" class="fixed inset-0 flex items-center justify-center z-50 hidden">
        <div class="absolute inset-0 bg-black bg-opacity-50" id="modalOverlay"></div>
        <div class="bg-white rounded-xl p-6 max-w-md w-full mx-4 relative z-10 transform transition-all">
            <div class="flex justify-end">
                <button id="closeModal" class="text-gray-400 hover:text-gray-600">
                    <i class="fa fa-times text-xl"></i>
                </button>
            </div>
            <div class="text-center mt-2">
                <div class="w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-4">
                    <i class="fa fa-check text-2xl text-success"></i>
                </div>
                <h3 class="text-lg font-semibold text-success">复制成功</h3>
                <p class="text-gray-600 mt-2">结果数据已复制到剪贴板</p>
            </div>
            <div class="mt-6">
                <button id="closeModalBtn" class="w-full bg-primary hover:bg-primary/90 text-white font-medium py-2 px-6 rounded-lg shadow transition-all duration-300">
                    确定
                </button>
            </div>
        </div>
    </div>

    <script>
        // 生成类似的oddsTable和multiplierMapping
        function generateSimilarJSON() {
            // 生成oddsTable
            const oddsTable = {};
            
            // 生成1-9的主键
            for (let i = 1; i <= 9; i++) {
                oddsTable[i] = {};
                // 子键范围8-12
                for (let j = 8; j <= 12; j++) {
                    // 计算值：基础值 * 主键系数 * 子键系数
                    let baseValue = 1000;
                    let mainKeyFactor = 1 / i;
                    let subKeyFactor = j / 8;
                    let value = Math.round(baseValue * mainKeyFactor * subKeyFactor);
                    
                    // 添加一些随机性，使结果更自然
                    value = Math.round(value * (0.9 + Math.random() * 0.2));
                    
                    oddsTable[i][j] = value;
                }
            }
            
            // 添加特殊的主键15
            oddsTable[15] = {};
            for (let j = 4; j <= 6; j++) {
                let value = Math.round(2000 * (j / 4) * (Math.random() * 0.3 + 0.85));
                oddsTable[15][j] = value;
            }
            
            // 生成multiplierMapping
            const multiplierMapping = {};
            
            // 主键10-13
            for (let i = 10; i <= 13; i++) {
                multiplierMapping[i] = [];
                // 每个主键对应5个值
                for (let j = 0; j < 5; j++) {
                    // 基础值根据主键递减
                    let baseValue = 1000 / (i - 9);
                    // 每个值递增
                    let increment = baseValue * (j + 1) / 5;
                    // 添加一些随机性
                    let value = Math.round((baseValue - increment) * (0.9 + Math.random() * 0.2));
                    
                    multiplierMapping[i].push(value);
                }
                // 确保值是递增的
                multiplierMapping[i].sort((a, b) => a - b);
            }
            
            return {
                oddsTable,
                multiplierMapping
            };
        }

        // 根据预期结果和初始乘数生成结果
        function generateResult(expectedResult, initialMultiplier, tolerance = 0.1) {
            // 验证输入参数
            if (isNaN(expectedResult) || expectedResult <= 0) {
                throw new Error("预期结果必须是正数");
            }
            
            if (isNaN(initialMultiplier)) {
                initialMultiplier = 1; // 默认初始乘数为1
            }
            
            // 使用之前的函数生成oddsTable和multiplierMapping
            const tables = generateSimilarJSON();
            const oddsTable = tables.oddsTable;
            const multiplierMapping = tables.multiplierMapping;
            
            // 计算结果的可接受范围
            const minResult = expectedResult * (1 - tolerance);
            const maxResult = expectedResult * (1 + tolerance);
            
            // 提取所有可能的基本数选项
            const baseOptions = [];
            for (const mainKey in oddsTable) {
                for (const subKey in oddsTable[mainKey]) {
                    baseOptions.push({
                        mainKey: parseInt(mainKey),
                        subKey: parseInt(subKey),
                        value: oddsTable[mainKey][subKey]
                    });
                }
            }
            
            // 提取所有可能的乘数选项
            const multiplierOptions = [];
            for (const mainKey in multiplierMapping) {
                for (const value of multiplierMapping[mainKey]) {
                    multiplierOptions.push({
                        mainKey: parseInt(mainKey),
                        value: value
                    });
                }
            }
            
            // 为了避免无限循环，设置最大尝试次数
            const maxAttempts = 5000;
            let attempts = 0;
            let bestResult = null;
            let minError = Infinity;
            
            // 尝试生成符合条件的结果
            while (attempts < maxAttempts) {
                // 随机选择基本数，直到总和接近预期结果
                let baseNumbers = [];
                let totalBase = 0;
                
                // 确定需要的基本数数量（2-5个）
                const numBaseNumbers = Math.floor(Math.random() * 4) + 2;
                
                // 随机选择基本数
                for (let i = 0; i < numBaseNumbers; i++) {
                    const randomIndex = Math.floor(Math.random() * baseOptions.length);
                    const option = baseOptions[randomIndex];
                    
                    // 检查这个选项是否已经被使用
                    const alreadyUsed = baseNumbers.some(item => 
                        item.mainKey === option.mainKey && item.subKey === option.subKey
                    );
                    
                    if (!alreadyUsed) {
                        baseNumbers.push(option);
                        totalBase += option.value;
                    } else {
                        // 如果已使用，尝试减少一次计数
                        i--;
                    }
                }
                
                // 确保至少有一个基本数
                if (baseNumbers.length === 0 && baseOptions.length > 0) {
                    baseNumbers.push(baseOptions[0]);
                    totalBase = baseOptions[0].value;
                }
                
                // 确定需要的乘数数量（0-3个）
                const numMultipliers = Math.floor(Math.random() * 4);
                let multipliers = [];
                let totalMultiplier = initialMultiplier;
                
                // 随机选择乘数
                for (let i = 0; i < numMultipliers; i++) {
                    const randomIndex = Math.floor(Math.random() * multiplierOptions.length);
                    const option = multiplierOptions[randomIndex];
                    
                    // 检查这个选项是否已经被使用
                    const alreadyUsed = multipliers.some(item => 
                        item.mainKey === option.mainKey && item.value === option.value
                    );
                    
                    if (!alreadyUsed) {
                        multipliers.push(option);
                        totalMultiplier += option.value;
                    } else {
                        // 如果已使用，尝试减少一次计数
                        i--;
                    }
                }
                
                // 计算最终结果
                const finalResult = totalBase * totalMultiplier;
                const error = Math.abs(finalResult - expectedResult) / expectedResult;
                
                // 检查结果是否在可接受范围内
                if (finalResult >= minResult && finalResult <= maxResult) {
                    // 找到了符合条件的结果
                    return {
                        oddsTable: oddsTable,
                        multiplierMapping: multiplierMapping,
                        baseNumbers: baseNumbers,
                        multipliers: multipliers,
                        totalBase: totalBase,
                        totalMultiplier: totalMultiplier,
                        finalResult: finalResult,
                        expectedResult: expectedResult,
                        error: error,
                        initialMultiplier: initialMultiplier
                    };
                }
                
                // 如果这是目前最好的结果，保存它
                if (error < minError) {
                    minError = error;
                    bestResult = {
                        oddsTable: oddsTable,
                        multiplierMapping: multiplierMapping,
                        baseNumbers: baseNumbers,
                        multipliers: multipliers,
                        totalBase: totalBase,
                        totalMultiplier: totalMultiplier,
                        finalResult: finalResult,
                        expectedResult: expectedResult,
                        error: error,
                        initialMultiplier: initialMultiplier
                    };
                }
                
                attempts++;
            }
            
            // 如果尝试了所有可能但仍未找到符合条件的结果，返回最佳结果
            if (bestResult) {
                // 尝试调整最佳结果以满足误差要求
                return adjustResultToMeetTolerance(bestResult, expectedResult, tolerance);
            }
            
            // 如果连最佳结果都没有，尝试使用更简单的组合
            return generateFallbackResult(expectedResult, initialMultiplier, tolerance);
        }
        
        // 调整结果以满足误差要求
        function adjustResultToMeetTolerance(result, expectedResult, tolerance) {
            const minResult = expectedResult * (1 - tolerance);
            const maxResult = expectedResult * (1 + tolerance);
            
            // 如果结果超出范围，尝试调整
            if (result.finalResult < minResult || result.finalResult > maxResult) {
                // 提取所有可能的基本数选项
                const baseOptions = [];
                for (const mainKey in result.oddsTable) {
                    for (const subKey in result.oddsTable[mainKey]) {
                        baseOptions.push({
                            mainKey: parseInt(mainKey),
                            subKey: parseInt(subKey),
                            value: result.oddsTable[mainKey][subKey]
                        });
                    }
                }
                
                // 提取所有可能的乘数选项
                const multiplierOptions = [];
                for (const mainKey in result.multiplierMapping) {
                    for (const value of result.multiplierMapping[mainKey]) {
                        multiplierOptions.push({
                            mainKey: parseInt(mainKey),
                            value: value
                        });
                    }
                }
                
                // 尝试最多100次调整
                for (let i = 0; i < 100; i++) {
                    // 决定是调整基本数还是乘数
                    const adjustBase = Math.random() < 0.7; // 70%概率调整基本数
                    
                    if (adjustBase && result.baseNumbers.length > 0) {
                        // 调整基本数
                        const indexToReplace = Math.floor(Math.random() * result.baseNumbers.length);
                        const oldBase = result.baseNumbers[indexToReplace];
                        
                        // 找到一个不同的基本数
                        let newBase = null;
                        do {
                            const randomIndex = Math.floor(Math.random() * baseOptions.length);
                            newBase = baseOptions[randomIndex];
                        } while (
                            newBase.mainKey === oldBase.mainKey && 
                            newBase.subKey === oldBase.subKey
                        );
                        
                        // 计算新的总和
                        const newTotalBase = result.totalBase - oldBase.value + newBase.value;
                        const newFinalResult = newTotalBase * result.totalMultiplier;
                        
                        // 如果新结果更接近预期值，接受这个变化
                        if (Math.abs(newFinalResult - expectedResult) < Math.abs(result.finalResult - expectedResult)) {
                            result.baseNumbers[indexToReplace] = newBase;
                            result.totalBase = newTotalBase;
                            result.finalResult = newFinalResult;
                            result.error = Math.abs(newFinalResult - expectedResult) / expectedResult;
                        }
                    } else if (multiplierOptions.length > 0) {
                        // 调整乘数
                        const addMultiplier = Math.random() < 0.5; // 50%概率添加乘数
                        
                        if (addMultiplier) {
                            // 添加一个新的乘数
                            const randomIndex = Math.floor(Math.random() * multiplierOptions.length);
                            const newMultiplier = multiplierOptions[randomIndex];
                            
                            // 检查是否已存在
                            const exists = result.multipliers.some(item => 
                                item.mainKey === newMultiplier.mainKey && 
                                item.value === newMultiplier.value
                            );
                            
                            if (!exists) {
                                result.multipliers.push(newMultiplier);
                                result.totalMultiplier += newMultiplier.value;
                                result.finalResult = result.totalBase * result.totalMultiplier;
                                result.error = Math.abs(result.finalResult - expectedResult) / expectedResult;
                            }
                        } else if (result.multipliers.length > 0) {
                            // 移除一个乘数
                            const indexToRemove = Math.floor(Math.random() * result.multipliers.length);
                            const removedMultiplier = result.multipliers[indexToRemove];
                            
                            result.multipliers.splice(indexToRemove, 1);
                            result.totalMultiplier -= removedMultiplier.value;
                            result.finalResult = result.totalBase * result.totalMultiplier;
                            result.error = Math.abs(result.finalResult - expectedResult) / expectedResult;
                        }
                    }
                    
                    // 检查是否满足误差要求
                    if (result.finalResult >= minResult && result.finalResult <= maxResult) {
                        return result;
                    }
                }
                
                // 如果调整后仍不满足要求，尝试更激进的方法
                return generateFallbackResult(expectedResult, result.initialMultiplier, tolerance);
            }
            
            return result;
        }
        
        // 生成备用结果，使用更简单的组合
        function generateFallbackResult(expectedResult, initialMultiplier, tolerance) {
            // 生成简单的结果，确保误差在可接受范围内
            const minResult = expectedResult * (1 - tolerance);
            const maxResult = expectedResult * (1 + tolerance);
            
            // 尝试生成一个基本数
            const baseNumber = Math.round(expectedResult / 10);
            
            // 尝试生成一个乘数
            const multiplier = Math.round(expectedResult / baseNumber) - initialMultiplier;
            
            // 创建简单的oddsTable和multiplierMapping
            const oddsTable = {
                1: {
                    1: baseNumber
                }
            };
            
            const multiplierMapping = {
                1: [multiplier]
            };
            
            // 创建结果对象
            const result = {
                oddsTable: oddsTable,
                multiplierMapping: multiplierMapping,
                baseNumbers: [
                    { mainKey: 1, subKey: 1, value: baseNumber }
                ],
                multipliers: [
                    { mainKey: 1, value: multiplier }
                ],
                totalBase: baseNumber,
                totalMultiplier: initialMultiplier + multiplier,
                finalResult: baseNumber * (initialMultiplier + multiplier),
                expectedResult: expectedResult,
                error: Math.abs(baseNumber * (initialMultiplier + multiplier) - expectedResult) / expectedResult,
                initialMultiplier: initialMultiplier
            };
            
            // 确保结果在可接受范围内
            if (result.finalResult < minResult) {
                // 结果太小，增加乘数
                const adjustment = Math.ceil((minResult - result.finalResult) / result.totalBase);
                result.multipliers[0].value += adjustment;
                result.totalMultiplier += adjustment;
                result.finalResult = result.totalBase * result.totalMultiplier;
                result.error = Math.abs(result.finalResult - expectedResult) / expectedResult;
            } else if (result.finalResult > maxResult) {
                // 结果太大，减少乘数
                const adjustment = Math.ceil((result.finalResult - maxResult) / result.totalBase);
                result.multipliers[0].value -= adjustment;
                result.totalMultiplier -= adjustment;
                result.finalResult = result.totalBase * result.totalMultiplier;
                result.error = Math.abs(result.finalResult - expectedResult) / expectedResult;
            }
            
            return result;
        }

        // 显示结果到界面
        function displayResult(result) {
            // 显示结果容器
            document.getElementById('resultContainer').classList.remove('hidden');
            
            // 更新结果摘要
            document.getElementById('expectedValue').textContent = result.expectedResult.toLocaleString();
            document.getElementById('finalValue').textContent = result.finalResult.toLocaleString();
            document.getElementById('errorRate').textContent = (result.error * 100).toFixed(1) + '%';
            
            // 生成计算方式的文本
            let baseNumbersText = result.baseNumbers.map(num => num.value).join(' + ');
            let multipliersText = result.multipliers.map(mult => mult.value).join(' + ');
            if (multipliersText) {
                multipliersText = result.initialMultiplier + ' + ' + multipliersText;
            } else {
                multipliersText = result.initialMultiplier.toString();
            }
            document.getElementById('calculationMethod').textContent = `(${baseNumbersText}) × (${multipliersText})`;
            
            // 更新基本数表格
            const baseTableBody = document.getElementById('baseNumbersTable');
            baseTableBody.innerHTML = '';
            
            result.baseNumbers.forEach((number, index) => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">${index + 1}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${number.mainKey}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${number.subKey}</td>
                    <td class="px-6 py-4 whitespace-nowrap font-medium">${number.value.toLocaleString()}</td>
                `;
                baseTableBody.appendChild(row);
            });
            
            document.getElementById('totalBase').textContent = result.totalBase.toLocaleString();
            
            // 更新乘数表格
            const multiplierTableBody = document.getElementById('multipliersTable');
            multiplierTableBody.innerHTML = '';
            
            result.multipliers.forEach((multiplier, index) => {
                const row = document.createElement('tr');
                row.className = 'hover:bg-gray-50 transition-colors';
                row.innerHTML = `
                    <td class="px-6 py-4 whitespace-nowrap">${index + 1}</td>
                    <td class="px-6 py-4 whitespace-nowrap">${multiplier.mainKey}</td>
                    <td class="px-6 py-4 whitespace-nowrap font-medium">${multiplier.value}</td>
                `;
                multiplierTableBody.appendChild(row);
            });
            
            document.getElementById('initialMultiplierValue').textContent = result.initialMultiplier;
            document.getElementById('totalMultiplierValue').textContent = result.totalMultiplier;
            
            // 更新JSON数据
            document.getElementById('jsonResult').textContent = JSON.stringify(result, null, 4);
            
            // 隐藏加载状态
            document.getElementById('loadingState').classList.add('hidden');
        }

        // 处理表单提交
        document.getElementById('generatorForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取输入值
            const expectedResult = parseFloat(document.getElementById('expectedResult').value);
            const initialMultiplier = parseFloat(document.getElementById('initialMultiplier').value);
            
            // 验证输入
            if (isNaN(expectedResult) || expectedResult <= 0) {
                alert('请输入有效的预期结果（必须是正数）');
                return;
            }
            
            // 隐藏结果和错误状态，显示加载状态
            document.getElementById('resultContainer').classList.add('hidden');
            document.getElementById('errorState').classList.add('hidden');
            document.getElementById('loadingState').classList.remove('hidden');
            
            // 使用setTimeout模拟异步操作，使加载状态可见
            setTimeout(() => {
                try {
                    // 生成结果
                    const result = generateResult(expectedResult, initialMultiplier);
                    
                    // 显示结果
                    displayResult(result);
                } catch (error) {
                    // 显示错误状态
                    document.getElementById('loadingState').classList.add('hidden');
                    document.getElementById('errorState').classList.remove('hidden');
                    document.getElementById('errorMessage').textContent = error.message || '生成结果时发生错误，请重试。';
                }
            }, 500);
        });

        // 处理复制结果按钮
        document.getElementById('copyResult').addEventListener('click', function() {
            const result = document.getElementById('jsonResult').textContent;
            
            // 复制到剪贴板
            navigator.clipboard.writeText(result).then(() => {
                // 显示成功模态框
                document.getElementById('successModal').classList.remove('hidden');
            }).catch(err => {
                console.error('复制失败: ', err);
                alert('复制失败，请手动复制。');
            });
        });

        // 关闭模态框
        document.getElementById('closeModal').addEventListener('click', function() {
            document.getElementById('successModal').classList.add('hidden');
        });
        
        document.getElementById('closeModalBtn').addEventListener('click', function() {
            document.getElementById('successModal').classList.add('hidden');
        });
        
        document.getElementById('modalOverlay').addEventListener('click', function() {
            document.getElementById('successModal').classList.add('hidden');
        });

        // 处理重新生成按钮
        document.getElementById('regenerate').addEventListener('click', function() {
            // 触发表单提交
            document.getElementById('generatorForm').dispatchEvent(new Event('submit'));
        });

        // 处理再试一次按钮
        document.getElementById('tryAgain').addEventListener('click', function() {
            document.getElementById('errorState').classList.add('hidden');
            document.getElementById('loadingState').classList.remove('hidden');
            
            setTimeout(() => {
                try {
                    const expectedResult = parseFloat(document.getElementById('expectedResult').value);
                    const initialMultiplier = parseFloat(document.getElementById('initialMultiplier').value);
                    const result = generateResult(expectedResult, initialMultiplier);
                    displayResult(result);
                } catch (error) {
                    document.getElementById('loadingState').classList.add('hidden');
                    document.getElementById('errorState').classList.remove('hidden');
                }
            }, 500);
        });
    </script>
</body>
</html>